{% extends "base.html" %}

{% block title %}管理员管理 - 学生管理系统{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 管理员数据
let admins = [];

// 加载管理员列表
async function loadAdmins() {
    try {
        const response = await fetch('/api/admin-users');
        if (!response.ok) {
            throw new Error('获取管理员列表失败');
        }
        admins = await response.json();
        renderAdminList();
    } catch (error) {
        console.error('加载管理员列表失败:', error);
        alert('加载管理员列表失败: ' + error.message);
    }
}

// 渲染管理员列表
function renderAdminList() {
    const tbody = document.getElementById('adminTableBody');
    tbody.innerHTML = '';
    
    admins.forEach(admin => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${admin.username}</td>
            <td>${admin.role}</td>
            <td>${formatDateTime(admin.created_at)}</td>
            <td>${admin.last_login ? formatDateTime(admin.last_login) : '从未登录'}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="editAdmin('${admin._id}')">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    ${admin.role !== 'super_admin' ? `
                    <button class="btn btn-outline-danger" onclick="deleteAdmin('${admin._id}', '${admin.username}')">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                    ` : ''}
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 格式化日期时间
function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 打开添加管理员模态框
function openAddAdminModal() {
    document.getElementById('adminForm').reset();
    document.getElementById('adminId').value = '';
    document.getElementById('modalTitle').textContent = '添加管理员';
    new bootstrap.Modal(document.getElementById('adminModal')).show();
}

// 编辑管理员
function editAdmin(adminId) {
    const admin = admins.find(a => a._id === adminId);
    if (!admin) return;
    
    document.getElementById('adminId').value = admin._id;
    document.getElementById('username').value = admin.username;
    document.getElementById('role').value = admin.role;
    document.getElementById('modalTitle').textContent = '编辑管理员';
    
    new bootstrap.Modal(document.getElementById('adminModal')).show();
}

// 删除管理员
function deleteAdmin(adminId, username) {
    if (!confirm(`确定要删除管理员 "${username}" 吗？此操作不可撤销。`)) {
        return;
    }
    
    fetch(`/api/admin-users/${adminId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error(data.error || '删除失败');
            });
        }
        return response.json();
    })
    .then(data => {
        alert('删除成功');
        loadAdmins();
    })
    .catch(error => {
        alert('删除失败: ' + error.message);
    });
}

// 提交管理员表单
document.getElementById('adminForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const adminId = document.getElementById('adminId').value;
    const data = {
        username: formData.get('username'),
        password: formData.get('password'),
        role: formData.get('role')
    };
    
    // 如果是编辑且密码为空，则不更新密码
    if (adminId && !data.password) {
        delete data.password;
    }
    
    try {
        const url = adminId ? `/api/admin-users/${adminId}` : '/api/admin-users';
        const method = adminId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '操作失败');
        }
        
        const result = await response.json();
        alert(result.message || '操作成功');
        document.getElementById('adminModal').querySelector('.btn-close').click();
        loadAdmins();
        
    } catch (error) {
        alert('操作失败: ' + error.message);
    }
});

// 页面加载时获取数据
document.addEventListener('DOMContentLoaded', function() {
    loadAdmins();
});
</script>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-user-shield me-2"></i>管理员管理</h2>
    <button class="btn btn-primary" onclick="openAddAdminModal()">
        <i class="fas fa-plus me-1"></i>添加管理员
    </button>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">管理员列表</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>创建时间</th>
                        <th>最后登录</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="adminTableBody">
                    <!-- 管理员数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加/编辑管理员模态框 -->
<div class="modal fade" id="adminModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">添加管理员</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="adminForm">
                <input type="hidden" id="adminId" name="id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password" name="password" 
                               placeholder="留空则不修改密码">
                        <div class="form-text">密码至少8位字符</div>
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">角色</label>
                        <select class="form-select" id="role" name="role" required>
                            <option value="admin">管理员</option>
                            <option value="super_admin">超级管理员</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.table th {
    background-color: #f8f9fa;
    border-top: none;
    font-weight: 600;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}
</style>
{% endblock %}
